//
//  PersistListViewController.swift
//  MyVideo
//
//  Created by han on 2021/4/22.
//

import UIKit
import AVFoundation
import AVKit


class PersistListViewController: UITableViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // 开启下载任务
        AssetPersistenceManager.shared.restorePersistenceManager()
        
        tableView.estimatedRowHeight = 75.0
        tableView.rowHeight = UITableView.automaticDimension
        NotificationCenter.default.addObserver(self, selector: #selector(handleAssetListManagerDidLoad(_:)), name: .AssetListManagerDidLoad, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: .AssetListManagerDidLoad, object: nil)
    }
    @objc func handleAssetListManagerDidLoad(_: Notification) {
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
}

extension PersistListViewController {
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    override func numberOfSections(in tableView: UITableView) -> Int { 1 }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { AssetListManager.shared.numberOfAssets() }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PersistListTableViewCell.reuseIdentifier, for: indexPath) as! PersistListTableViewCell
        let asset = AssetListManager.shared.asset(indexPath.row)
        cell.asset = asset
        cell.delegate = self
        return cell
    }
    
    override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
        guard let cell = tableView.cellForRow(at: indexPath) as? PersistListTableViewCell, let asset = cell.asset
            else { return }
        
        let downloadState = AssetPersistenceManager.shared.downloadState(for: asset)
        let alertAction: UIAlertAction

        switch downloadState {
        case .notDownloaded:
            alertAction = UIAlertAction(title: "Download", style: .default) { _ in
                AssetPersistenceManager.shared.downloadStream(for: asset)
            }

        case .downloading:
            alertAction = UIAlertAction(title: "Cancel", style: .default) { _ in
                AssetPersistenceManager.shared.cancleDownload(asset)
            }

        case .downloaded:
            alertAction = UIAlertAction(title: "Delete", style: .default) { _ in
                AssetPersistenceManager.shared.deleteAsset(asset)
            }
        }

        let alertController = UIAlertController(title: asset.stream.name, message: "Select from the following options:",
                                                preferredStyle: .actionSheet)
        alertController.addAction(alertAction)
        alertController.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))

        if UIDevice.current.userInterfaceIdiom == .pad {
            guard let popoverController = alertController.popoverPresentationController else {
                return
            }

            popoverController.sourceView = cell
            popoverController.sourceRect = cell.bounds
        }

        present(alertController, animated: true, completion: nil)
    }
}

extension PersistListViewController: PersistListTableViewCellDelegate {
    func assetListTableViewCell(_ cell: PersistListTableViewCell, downloadStateDidChange newState: Asset.DownloadState) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        tableView.reloadRows(at: [indexPath], with: .automatic)
    }
}
